<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/8/23
 * Time: 15:25
 */

namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\services\message\ManualWechatMessage;
use common\models\datas\CardAttr;
use common\models\datas\CardSend;
use common\models\datas\Customer;
use zhtfrontend\models\datas\Scholarapply;
use yii\helpers\Json;
use yii\web\NotFoundHttpException;
use yii\web\Response;
use yii\data\Pagination;
use yii\widgets\ActiveForm;


class ScholarapplyController extends \zhtfrontend\components\bases\BaseController
{
    public function actionIndex()
    {
        $param['searchData'] = \Yii::$app->request->get();
        $pageSize = isset($param['pageSize']) ? $param['pageSize'] : 12;
        $data = Scholarapply::find()->orderBy('id DESC');
        if (!empty($param['searchData'])) {
            $search_data = $param['searchData'];
            if (!empty($search_data['name'])) {
                $cids = Customer::find()->select('id')->where(['like', 'name', $search_data['name']])->andWhere(['site_id' => Fun::getSiteId()])->column();
                $data->andWhere(['customer_id' => $cids]);
            }
            if (isset($search_data['status']) && $search_data['status'] != null) {
                $data->andWhere(['status' => $search_data['status']]);
            }
        }
        $pages = new Pagination(['totalCount' => $data->count(), 'pageSize' => $pageSize]);
        isset($param['page']) ? $pages->page = $param['page'] - 1 : 0;
        $model = $data->offset($pages->offset)->limit($pages->limit)->all();
        $list = Fun::asArray($model, ['customer_name', 'operate', 'v_code']);

        return $this->render('index', ['data' => $list, 'pages' => $pages]);
    }

    public function actionHandle()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Scholarapply::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        if ($model->status == 0) {
            $model->status = 1;
        }
        $model->scenario = 'handle';

        //ajax验证
        if (\Yii::$app->request->isAjax && \Yii::$app->request->post('ajax') == 'w0' && $model->load(\Yii::$app->request->post())) {
            \Yii::$app->response->format = Response::FORMAT_JSON;
            return ActiveForm::validate($model);
        }
        if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
            $model->admin_id = \Yii::$app->user->id;
            $model->admin_name = \Yii::$app->user->identity->name;
            $title = '申请处理';
            $str = '您于' . \Yii::$app->formatter->asDatetime($model->created_at) . "申请的激活码 \n 状态：";
            if ($model->status == 2) {
                $str .= "申请成功\n";
            } elseif ($model->status == 3) {
                $str .= "申请失败 \n";
            }
            if (!empty($model->remarks)) {
                $str .= "描述：" . $model->remarks;
            }
            if ($model->status == 2) {
                $CartModel = CardAttr::find()->where(['sendtype' => 2, 'salesman_id' => 0, 'customer_id' => NULL, 'site_id' => $model->site_id])->orderBy('id ASC')->one();
                if ($CartModel != null) {
                    $model->cardcode_id = $CartModel->id;
                    if ($model->save(false)) {
                        $CartModel->salesman_id = $model->customer_id;
                        $CartModel->issuser_id = $model->customer_id;
                        $CartModel->obtain_type = 2;
//                        $CartModel->site_id = Fun::getSiteId();
                        $CartModel->save(false);

                        $CardSendModel = new CardSend();
                        $CardSendModel->number = 1;
                        $CardSendModel->user_id = \Yii::$app->user->id;
                        $CardSendModel->salesman_id = $model->customer_id;
                        $CardSendModel->issuser_id = $model->customer_id;
                        $CardSendModel->send_type = 1;
                        $CardSendModel->batch_id = $CartModel->batch_id;
                        $CardSendModel->card_start = $CartModel->card_id;
                        $CardSendModel->card_end = $CartModel->card_id;
                        $CardSendModel->site_id = Fun::getSiteId();
                        $CardSendModel->save(false);

                        (new ManualWechatMessage([
                            'customer_id' => $model->customer_id,
                            'title' => $title,
                            'desc' => $str,
                            'url' => '/scholarapply/list?site_id=' . Fun::getSiteId(),
                            'site_id' => Fun::getSiteId()
                        ]))->send();

                        return $this->redirectMessage('操作成功', Fun::url(['scholarapply/index']));
                    }
                } else {
                    return $this->redirectMessage('操作失败，推荐激活码不错存在', Fun::url(['scholarapply/index']));
                }
            } else {
                if ($model->save(false)) {
                    if ($model->status == 3) {
                        (new ManualWechatMessage([
                            'customer_id' => $model->customer_id,
                            'title' => $title,
                            'desc' => $str,
                            'url' => '/scholarapply/list?site_id=' . Fun::getSiteId()
                        ]))->send();
                    }
                    return $this->redirectMessage('操作成功', Fun::url(['scholarapply/index']));
                }
            }

        }
        return $this->render('handle', ['model' => $model]);
    }

    public function actionView()
    {
        $this->layout = '@app/views/layouts/iframe.php';
        $id = \Yii::$app->request->get('id');
        if ($id == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }
        $model = Scholarapply::findOne($id);
        if ($model == null) {
            throw new NotFoundHttpException(\Yii::t('zhtfrontend', '信息不存在'));
        }

        return $this->render('view', ['model' => $model]);
    }


}